package com.zhinan.shiro.filter;

import cn.hutool.core.util.StrUtil;
import com.zhinan.common.SysConstant;
import com.zhinan.common.SysEnum;
import com.zhinan.exception.ZhiNanException;
import com.zhinan.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 图形验证码过滤器
 * @Author: ZhiNan
 * @Date: 2023-04-21 13:16
 * @Version: 1.0
 */
@Slf4j
public class CaptchaValidateFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        //从session中获取验证码信息
        Object codeSession = SessionUtil.getObjectFromSession(SysConstant.KAPTCHA_SESSION_KEY);
        String code = String.valueOf(codeSession != null ? codeSession : SysConstant.BLANK_STRING);

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String result = httpServletRequest.getParameter("validateCode");
        SessionUtil.delObjetFromSession(SysConstant.KAPTCHA_SESSION_KEY);  //从Session中删除  避免被多次使用
        if (StrUtil.isEmpty(result) || !result.equalsIgnoreCase(code)) {
            return false;

        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        log.error("验证码不匹配");
        return false;
    }
}
